package com.aids_malaria.ui.setting;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.aids_malaria.R;
import com.aids_malaria.adapter.PadManagerAdapter;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.Pad;
import com.aids_malaria.http.response.RoleAuth;
import com.aids_malaria.util.AuthUtil;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.titlebar.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class PadSettingActivity extends BaseActivity implements PadManagerAdapter.Option {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_pad_id)
    EditText et_pad_id;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    private List<Pad> mData = new ArrayList<>();
    private List<Pad> mOriginalData = new ArrayList<>();
    private PadManagerAdapter padManagerAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pad_setting;
    }

    @Override
    protected void onResume() {
        super.onResume();
        getPad();
    }

    @Override
    protected void initView() {
        super.initView();
        initTitleBar(title_bar, ResourceUtil.getString(R.string.setting_pad));
        initRefreshLayout();
        et_pad_id.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String inputStr = charSequence.toString();
                mData.clear();
                for(int j=0; j<mOriginalData.size(); j++){
                    if(mOriginalData.get(j).getPad_id().contains(inputStr)){
                        mData.add(mOriginalData.get(j));
                    }
                }
                padManagerAdapter.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        initRecycleView();
    }

    private void initRefreshLayout() {
        refresh_layout.setEnableLoadMore(false);
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishLoadMore(1500);
                if (!AuthUtil.isHaveQueryAuthByCode(Constant.SETTING_PAD_SEQ)){
                    ToastUtil.showNoPermission();
                    return;
                }
                getPad();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishRefresh(1000);
                if (!AuthUtil.isHaveQueryAuthByCode(Constant.SETTING_PAD_SEQ)){
                    ToastUtil.showNoPermission();
                    return;
                }
                getPad();
            }
        });
    }

    private void initRecycleView() {
        rv_data.setLayoutManager(new LinearLayoutManager(mContext));
        padManagerAdapter = new PadManagerAdapter(mContext,R.layout.item_pad_manager,mData,this);
        rv_data.setAdapter(padManagerAdapter);
        padManagerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Bundle bundle = new Bundle();
                bundle.putBoolean(PadManagerCreateEditActivity.KEY_IS_CREATE, false);
                bundle.putSerializable(PadManagerCreateEditActivity.KEY_PAD,mData.get(position));
                startActivity(PadManagerCreateEditActivity.class,bundle);
            }
        });
    }

    @OnClick({R.id.iv_add})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_add:
                if (!AuthUtil.isHaveInsertAuthByCode(Constant.SETTING_PAD_SEQ)){
                    ToastUtil.showNoPermission();
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putBoolean(PadManagerCreateEditActivity.KEY_IS_CREATE, true);
                bundle.putString(PadManagerCreateEditActivity.KEY_SEQ, "" + (mData.size() + 1));
                startActivity(PadManagerCreateEditActivity.class,bundle);
                break;
        }
    }

    /**
     * 获取pad数据
     */
    private void getPad(){
        if (!AuthUtil.isHaveQueryAuthByCode(Constant.SETTING_PAD_SEQ)){
            return;
        }
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getPad()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<Pad>>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(List<Pad> list) throws Exception {
                        mData.clear();
                        mData.addAll(list);
                        mOriginalData.clear();
                        mOriginalData.addAll(list);
                        padManagerAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    @Override
    public void onItemclick(int position) {
        Pad pad =  mData.get(position);
        if (!AuthUtil.isHaveUpdateAuthByCode(Constant.SETTING_PAD_SEQ)){
            ToastUtil.showNoPermission();
            return;
        }
        pad.setIs_check(pad.getIs_check() == 0? 1:0);
        String dataJson = GsonUtil.beanToJson(pad);
        savePad("2",dataJson, pad);
    }

    /**
     * 新增、编辑pad    保存类型 1插入 2更改 3 删除
     * @param type
     * @param data
     */
    private void savePad(String type,String data,Pad pad){
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data);
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).savePad(type,requestBody)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<Object>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(Object object) throws Exception {
                        ToastUtil.showToast(ResourceUtil.getString(R.string.operate_success));
                        ArrayList<Pad> list = new ArrayList();
                        list.addAll(mData);
                        mData.clear();
                        for (int i = 0; i < list.size(); i++) {
                            Pad obj = list.get(i);
                            if (obj.getPad_id().equals(pad.getPad_id())){
                                mData.add(pad);
                            }else{
                                mData.add(obj);
                            }
                        }
                        padManagerAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }
}
